package com.example.blecommunicate;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.a1anwang.okble.client.core.OKBLEDevice;
import com.a1anwang.okble.client.core.OKBLEDeviceImp;
import com.a1anwang.okble.client.core.OKBLEDeviceListener;
import com.a1anwang.okble.client.core.OKBLEOperation;
import com.a1anwang.okble.client.scan.BLEScanResult;

import java.util.UUID;

public class MainActivity extends AppCompatActivity implements OKBLEDeviceListener {
    private String TAG = "MainActivity";
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private BluetoothDevice mBlueDevice;
    private OKBLEDevice mOkbleDevice;
    //private final String FIRST_DEVICE_MAC = "02:00:10:01:00:33";
    private final String FIRST_DEVICE_MAC = "EE:A7:F6:86:9D:AF";
    static int times = 0;
    Button btWrite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        openBluetooth(); //打开蓝牙设备
        connectDevice(FIRST_DEVICE_MAC);  //连接设备
        //写命令
        btWrite = this.findViewById(R.id.btWrite);
        btWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOkbleDevice.addWriteOperation("1001","42",null);
            }
        });

    }

    /**
     * step1.其实在这之前还得请求用户打开位置等权限，才能连接蓝牙设备
     * step2.打开蓝牙开关
     *
     */
    private void openBluetooth() {
        if (mBluetoothAdapter == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
            mBluetoothAdapter = mBluetoothManager.getAdapter();
        }
        if (mBluetoothAdapter !=null && !mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

    @Override
    protected void onDestroy() {
        setNofity("","1002",false);
        super.onDestroy();
    }

    /**
     * 连接蓝牙设备
     * @param mac ：设备的mac地址
     * @return
     */
    boolean connectDevice(String mac){
        mBlueDevice = mBluetoothAdapter.getRemoteDevice(mac);
        BLEScanResult bleScanResult = new BLEScanResult(mBlueDevice, new byte[31],0);

        if(bleScanResult!=null) {
            mOkbleDevice = new OKBLEDeviceImp(this, bleScanResult);
            mOkbleDevice.addDeviceListener(this);
            mOkbleDevice.connect(true);
        }
        return true;
    }

    public void setNofity(String strServiceUUID,String strCharacteristicUUID,boolean enable){
      //  UUID serviceUUID = UUID.fromString(strServiceUUID);
       // UUID characteristicUUID = UUID.fromString(strCharacteristicUUID);

        mOkbleDevice.addNotifyOrIndicateOperation(strCharacteristicUUID, enable, new OKBLEOperation.NotifyOrIndicateOperationListener() {
            @Override
            public void onNotifyOrIndicateComplete() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG,"onNotifyOrIndicateComplete");
                    }
                });
            }

            @Override
            public void onFail(int code, final String errMsg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG,"NotifyOrIndicate onFail:"+ errMsg);
                    }
                });
            }

            @Override
            public void onExecuteSuccess(OKBLEOperation.OperationType type) {
                Log.i(TAG,"onExecuteSuccess");
            }
        });
    }


    @Override
    public void onConnected(String deviceTAG) {
        times++;
      //  if(times == 1)
         setNofity("","1002",true);
        Log.i(TAG,"onConnected deviceTAG="+deviceTAG+",times="+times);

    }

    @Override
    public void onDisconnected(String deviceTAG) {
        Log.i(TAG,"onDisconnected deviceTAG="+deviceTAG);
    }

    @Override
    public void onReadBattery(String deviceTAG, int battery) {
        Log.i(TAG,"onReadBattery deviceTAG="+deviceTAG+",bettery="+battery);
    }

    @Override
    public void onReceivedValue(String deviceTAG, String uuid, byte[] value) {
        Log.i(TAG,"onReceivedValue deviceTAG="+deviceTAG+",uuid="+uuid+",value="+ByteUtils.byteToHexString(value));
    }

    @Override
    public void onWriteValue(String deviceTAG, String uuid, byte[] value, boolean success) {
        Log.i(TAG,"onWriteValue deviceTAG="+deviceTAG+",uuid="+uuid+",value="+ByteUtils.byteToHexString(value)+",success="+success);
    }

    @Override
    public void onReadValue(String deviceTAG, String uuid, byte[] value, boolean success) {
        Log.i(TAG,"onReadValue deviceTAG="+deviceTAG+",uuid="+uuid+",value="+ByteUtils.byteToHexString(value)+",success="+success);
    }

    @Override
    public void onNotifyOrIndicateComplete(String deviceTAG, String uuid, boolean enable, boolean success) {

    }
}